package org.springframework.beans.factory.config;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.anno.Autowired;
import org.springframework.beans.factory.anno.Value;

import java.io.Serializable;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

/**
 * @author:刘仁有
 * @desc:
 * @email:953506233@qq.com
 * @data:2019/12/14
 */
public class CommonAnnotationBeanPostProcessor implements PropertyValueBeanDefinitionPostProcessor, BeanFactoryAware, Serializable {
    @Override
    public void setBeanFactory(BeanFactory beanFactory) {

    }
    //处理@Value 属性
    @Override
    public void postProcessBeanDefinitionPropertyValue(BeanDefinition beanDefinition, Class<?> beanType, String beanName) {
        Field[] fields = beanType.getDeclaredFields();
        List<PropertyValue> pvs = beanDefinition.getPropertyValues();
        if(null==pvs||pvs.isEmpty()){
            pvs = new ArrayList<>();
        }
        for (Field field:fields) {
            if(field.isAnnotationPresent(Value.class)){
                pvs.add(new PropertyValue(field.getName(),field.getAnnotation(Value.class).value()));
            }
        }
        beanDefinition.setPropertyValues(pvs);
    }
}
